package com.example.androidmsg;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.KeyEventDispatcher;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.androidmsg.Msg.MyHandler;
import com.example.androidmsg.Utils.Myalarm;
import com.example.androidmsg.Utils.PermissUtil;
import com.example.androidmsg.romUtils.FloatWindowManager;
import com.example.androidmsg.seiveces.ForeService;
import com.example.androidmsg.view.MyImageView;
import com.example.androidmsg.view.WindowHeadToast;
import com.example.lib.socket.Mpoint;
import com.example.lib.socket.MyClientSocket;
import com.example.lib.socket.MyServiceSocket;
import com.example.lib.socket.Mycallback;
import com.example.lib.socket.OcrData;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";
    //保存图片的路径
   // public final String DCIM = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
    public  String DCIM;
   public EditText et1;
    public EditText et2;
    public TextView tv1;
    public TextView tvStatus;
    public Button bu0;
    public Button bu1;
    public Button bu2;
    MyServiceSocket serSocket;
    MyClientSocket cSocket;
    public MyHandler chandler;
    MyHandler shandler;

    MyImageView iv1;
    MediaPlayer mMediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        iv1=findViewById(R.id.iv1);
        tvStatus=findViewById(R.id.tvStatus);
        et1=findViewById(R.id.et1);
        et2=findViewById(R.id.et2);
        tv1=findViewById(R.id.tv1);
        bu0=findViewById(R.id.bu0);
        bu1=findViewById(R.id.bu1);
        bu2=findViewById(R.id.bu2);

        setOn();
        PermissUtil.appleMin(this,Manifest.permission.INTERNET);
        PermissUtil.appleMin(this,Manifest.permission.ACCESS_WIFI_STATE);
        DCIM=getFilesDir().toString(); // 获取应用的内部存储目录;
        //Bitmap bm=BitmapFactory.decodeFile(DCIM+"/");
        //iv1.setImageBitmap(bm);

        intent(this);
        startServices();

        FloatWindowManager.getInstance().applyOrShowFloatWindow(this);
        // 检查权限是否被授予
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
//            // 请求权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, MY_PERMISSIONS_REQUEST_INTERNET);
//        } else {
//            // 权限已经被授予，可以进行网络操作
//        }

    }
    public void showImg(String fileName){
        Bitmap bm=BitmapFactory.decodeFile(DCIM+"/"+fileName);
        iv1.setImageBitmap(bm);
    }

    public  void setOn(){
        doMsg();
        Mycallback iv1Call=new Mycallback() {
            @Override
            public void MyCall(OcrData od) {
                if (od.list.size()>0){
                    String s1="";
                    Mpoint p=od.list.get(0);
                    String formattedString = String.format("x:%.0f,y:%.0f", p.x,p.y);
                    cSocket.data=formattedString.toString();

                }
            }
        };
        iv1.call=iv1Call;
        bu0 .setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.startThread(MainActivity.this);



            }
        });
          bu1.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  if (mMediaPlayer!=null&&mMediaPlayer.isPlaying()){
                      mMediaPlayer.stop();
                      mMediaPlayer.reset();     //重置MediaPlayer
                      mMediaPlayer.release();   //释放MediaPlayer
                      mMediaPlayer=null;
                      Log.d(TAG, "test1");
                  }

              }
          });

        bu2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myBinder.sendData(MainActivity.this);


            }
        });
    }

  @SuppressLint("HandlerLeak")
  public void doMsg(){
       chandler = new MyHandler(){
           @Override
           public void handleMessage(@NonNull Message msg) {
               OcrData od = (OcrData ) msg.obj; // 获取消息数据
               switch (od.msgId) {
                   case -1:
                       show(MainActivity.this,od.ImgStr);
                       tvStatus.setText("连接断开");
                       cSocket=null;
                       bu0.setText("开启服务");
                       break;
                   case -2:
                       show(MainActivity.this,od.ImgStr);
                       Toast.makeText(MainActivity.this, "head错误", Toast.LENGTH_SHORT).show();

                       break;
                   case 1:

                       tvStatus.setText("连接到pc");

                       break;
                   case 2:
                       tvStatus.setText("连接到服务器");
                       break;

                   case 3:
                       show(MainActivity.this,od.ImgStr);
                       //tv1.setText(tv1.getText().toString()+"\n"+od.ImgStr);
                       tv1.setText("服务返回数据\n"+od.ImgStr);
                       break;
                   case 4:
                       tvStatus.setText(od.ImgStr);
                       Toast.makeText(MainActivity.this, "未连接到pc", Toast.LENGTH_SHORT).show();
                       break;
                   case 5:
                       show(MainActivity.this,od.ImgStr);
                       tvStatus.setText(od.ImgStr);
                       Toast.makeText(MainActivity.this, od.ImgStr, Toast.LENGTH_SHORT).show();
                       break;
                   case 6:
                       showImg(od.ImgStr);
                       Toast.makeText(MainActivity.this, "接收到图片", Toast.LENGTH_SHORT).show();
                       break;
                   case 7:

                       Toast.makeText(MainActivity.this, od.ImgStr, Toast.LENGTH_SHORT).show();
                       break;
                   case 8:

                       Toast.makeText(MainActivity.this, od.ImgStr, Toast.LENGTH_SHORT).show();
                       break;
                   // 其他消息类型的处理
               }


           }

           @Override
           public void MyCall(OcrData od) {
               Message msg=new Message();
               msg.what=1;
               msg.obj=od;
               sendMessage(msg);

           }


       };




      shandler = new MyHandler(){
          @Override
          public void MyCall(OcrData od) {
              Message msg=new Message();
              msg.what=2;
              msg.obj=od;
              sendMessage(msg);
          }

          @Override
          public void handleMessage(@NonNull Message msg) {
              switch (msg.what) {
                  case 2:
                      OcrData od = (OcrData ) msg.obj; // 获取消息数据
                      if (od.ImgStr!=null){
                          tv1.setText(tv1.getText().toString()+"\n"+od.ImgStr);
                      }else{
                          Toast.makeText(MainActivity.this, "没有数据", Toast.LENGTH_SHORT).show();

                      }
                      break;
                  // 其他消息类型的处理
              }


          }
      };

  }
    private ForeService.MyBinder myBinder;

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("test","test0");
            myBinder = (ForeService.MyBinder) service;
            myBinder.startDownload();
        }
    };

  public void startServices(){


      Intent intent = new Intent().setClass(this, ForeService.class);
      bindService(intent, connection, Context.BIND_AUTO_CREATE);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          startForegroundService(intent);
      } else {
          startService(intent);
      }
  }


    private boolean intent(Context context) {//判断应用的通知权限是否打开，返回Boolean值

        if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) {
            Intent localIntent = new Intent();
            //判断API，跳转到应用通知管理页面
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0及以上
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
            }
            context.startActivity(localIntent);
            return false;
        }
        return true;
    }


    public void show(Context context,  String msg) {

       String title="msg";
          startAlarm();


          WindowHeadToast windowHeadToast = new WindowHeadToast(this);
          windowHeadToast.showCustomToast();



        if (intent(context)) {

            Intent intent = new Intent(context, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationManager manager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= 26) {//API26以上的方法
                NotificationChannel channel = new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_HIGH);
                manager.createNotificationChannel(channel);
                notification = new Notification.Builder(context, "id")
                        .setContentTitle(title)
                        .setContentText(msg)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setNumber(3) // 自定义桌面通知数量
                        .setVisibility(Notification.VISIBILITY_PRIVATE) // 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
                        .setContentIntent(pi)
                        .build();
            } else {//API26以下
                notification = new Notification.Builder(context)
                        .setContentTitle(title)
                        .setContentText(msg)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setNumber(3) // 自定义桌面通知数量
                        .setContentIntent(pi)
                        .build();
            }

            manager.notify(2, notification);
        }

    }
    /**
     * 播放系统默认闹钟铃声
     *
     * @return MediaPlayer对象
     *
     * @throws Exception
     */
    private void startAlarm() {
       if (mMediaPlayer==null){
           mMediaPlayer = MediaPlayer.create(this, getSystemDefultRingtoneUri());
           mMediaPlayer.setLooping(true);
       }else{
           mMediaPlayer.setLooping(true);
       }
//        try {
//            mMediaPlayer.prepare();
//
//        } catch (IllegalStateException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        if (!mMediaPlayer.isPlaying()){
            mMediaPlayer.start();
        }

    }
    //获取系统默认铃声的Uri
    private Uri getSystemDefultRingtoneUri() {
        return RingtoneManager.getActualDefaultRingtoneUri(this,
                RingtoneManager.TYPE_RINGTONE);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mMediaPlayer!=null&&mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
            mMediaPlayer.reset();     //重置MediaPlayer
            mMediaPlayer.release();   //释放MediaPlayer
            mMediaPlayer=null;
            Log.d(TAG, "test2");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer!=null&&mMediaPlayer.isPlaying()){
            mMediaPlayer.stop();
            mMediaPlayer.reset();     //重置MediaPlayer
            mMediaPlayer.release();   //释放MediaPlayer
            mMediaPlayer=null;
            Log.d(TAG, "test2");
        }
    }
}